/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cumulusCloud.knowledge;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import cumulusCloud.common.InformationServer;
import cumulusCloud.common.ManageConfiguration;
import cumulusCloud.common.objects.CloudConfiguration;


public class ServerKnow {
	private static Logger logger = java.util.logging.Logger.getLogger(InformationServer.class.getName());
	
	static private ServerKnow instance;
	
	public static ServerKnow getInstance() {
		if (instance == null) instance = new ServerKnow();
		return instance;
	}
	
	private ServerKnow() {
		
	}

	private String lastInternetIP;
	private Date lastInternetIPResolve;
	private Boolean directIP = null;
	
	public synchronized String getInternetIP() {
		if ( (lastInternetIPResolve == null) || (new Date().getTime() - lastInternetIPResolve.getTime() > 600000) ) {
			logger.fine("Getting the internet IP");
			
			if ( (directIP == null) || (directIP == false) ) {
				try {
					URL url = new URL("http://checkip.cumuluscloud.cc");
					BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
					lastInternetIP = br.readLine();
					logger.log(Level.FINE, "The retrieved internet IP is {0}", lastInternetIP);
					lastInternetIPResolve = new Date();
				} catch (NoRouteToHostException e) {
					logger.warning("Could not contact remote server");
				} catch (Exception e) {
					logger.warning("Could not retrieve the IP");
					lastInternetIP = null;
				}
				
				if ( (directIP == null) && (lastInternetIP != null)) {
					try {
						String local = InetAddress.getLocalHost().getHostAddress();
						logger.log(Level.FINE, "The interface IP is {0}", local);
						
						if (local.equals(lastInternetIP)) {
							logger.fine("The interface IP is the same as the Internet one. Use direct IP");
							directIP = true;
						} else {
							logger.fine("The interface IP is not the same as the Internet one. Not using direct IP");
							directIP = false;
						}
					} catch (UnknownHostException e) {
						logger.warning("Could not get the interface IP");
					}
				}
			} else {
				try {
					lastInternetIP = InetAddress.getLocalHost().getHostAddress();
					logger.log(Level.FINE, "The interface IP is {0}", lastInternetIP);
				} catch (UnknownHostException e) {
					logger.warning("Could not get the interface IP");
					lastInternetIP = null;
				}
			}
		}
		
		return lastInternetIP;
	}
	
	public String getInternetBaseURL() {
		String result;
		
		result = getInternetSecureBaseURL();
		if (result != null) return result;
		
		return getInternetNonSecureBaseURL();
	}
	
	public String getInternetNonSecureBaseURL() {
		String result = "http://";
		CloudConfiguration cc = ManageConfiguration.getCurrentConfig();
		
		if (cc.httpPort == -1) {
			return null;
		}
		
		String hostName = ManageConfiguration.getCurrentConfig().hostName;
		if ( (hostName == null) || (hostName.isEmpty()) ) {
			result += getInternetIP();
		} else {
			result += hostName;
		}
		
		if (cc.httpPort != 80) result += ":" + cc.httpPort;
		
		result += "/";
		
		return result;
	}
	
	public String getInternetSecureBaseURL() {
		String result = "https://";
		CloudConfiguration cc = ManageConfiguration.getCurrentConfig();
		
		if (cc.httpsPort == -1) {
			return null;
		}
		
		String hostName = ManageConfiguration.getCurrentConfig().hostName;
		if ( (hostName == null) || (hostName.isEmpty()) ) {
			result += getInternetIP();
		} else {
			result += hostName;
		}
		
		if (cc.httpsPort != 443) result += ":" + cc.httpsPort;
		
		result += "/";
		
		return result;
	}
}
